package mianshi;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangmaolin1
 * @date 2022/1/15 下午12:06
 */
public class PrintNum {

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();

        AtomicInteger num = new AtomicInteger(1);
        new Thread(() -> {
            lock.lock();
            try {
                System.out.println("0获取锁");
                while (num.get() <= 4) {
                    System.out.println("condition1 await");
                    condition1.await();
                    System.out.println("condition1 wake");

                    System.out.println(Thread.currentThread().getName() + "," + num.getAndIncrement());
                    System.out.println("condition2 signal");

                    condition2.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("0释放锁");

                lock.unlock();
            }

        }).start();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println("1获取锁");
                while (num.get() <= 4) {
                    System.out.println("condition1 signal");
                    condition1.signal();
                    System.out.println(Thread.currentThread().getName() + "," + num.getAndIncrement());
                    System.out.println("condition2 await");

                    condition2.await();
                    System.out.println("condition2 wake");

                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("1释放锁");
                lock.unlock();
            }
        }).start();
    }
}
